package com.cool.orchestration.service.impl;

import com.cool.common.model.request.BaseApiRequest;
import com.cool.common.model.response.BaseApiResponse;
import com.cool.orchestration.api.ThirdPartyApiService;
import com.cool.orchestration.service.IThirdPartyApiServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ThirdPartyApiServiceFactory<T extends BaseApiRequest, E> implements IThirdPartyApiServiceFactory<T, E>  {


    private final ApplicationContext applicationContext;

    private final Map<String, ThirdPartyApiService<T, E>> serviceCache = new ConcurrentHashMap<>();

    @Autowired
    public ThirdPartyApiServiceFactory(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    @SuppressWarnings("unchecked")
    public ThirdPartyApiService<T, E> getService(String interfaceName) {
        return serviceCache.computeIfAbsent(interfaceName, name -> {
            // 根据命名约定查找Bean，例如interfaceName="alipay"对应AlipayThirdPartyApiService
            String beanName = this.getBeanName(name);
            try {

                return applicationContext.getBean(beanName, ThirdPartyApiService.class);
            } catch (Exception e) {
                throw new IllegalArgumentException("No ThirdPartyApiService implementation found for interface: " + name);
            }
        });
    }

    /**
     * 从完整类名中提取简单类名并将首字母小写
     * @param interfaceName 接口名称，例如 "travelsky.ce.QueryDuplicateFlightCodeShareAgreementList"
     * @return 处理后的类名，例如 "queryDuplicateFlightCodeShareAgreementList"
     */
    private String getBeanName(String interfaceName) {
        if (interfaceName == null || interfaceName.isEmpty()) {
            return interfaceName;
        }

        // 提取简单类名（最后一个点后面的部分）
        String simpleName = interfaceName.substring(interfaceName.lastIndexOf('.') + 1);

        // 如果类名为空，直接返回
        if (simpleName.isEmpty()) {
            return simpleName;
        }

        // 将首字母小写
        return Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1) + "Service";
    }
}
